<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书列表展示</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/list.css">
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script src="js/jq-paginator.js"></script>

</head>

<body>
    <div class="bookContainer">
        <h2>图书列表展示</h2>
        <div class="navbar-justify-between">
            <div>
                <button class="btn btn-outline-info" type="button" onclick="location.href='book_add.html'">添加图书</button>
                <button class="btn btn-outline-info" type="button" onclick="batchDelete()">批量删除</button>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <td>选择</td>
                    <td class="width100">图书ID</td>
                    <td>书名</td>
                    <td>作者</td>
                    <td>数量</td>
                    <td>定价</td>
                    <td>出版社</td>
                    <td>状态</td>
                    <td class="width200">操作</td>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>

        <div class="demo">
            <ul id="pageContainer" class="pagination justify-content-center"></ul>
        </div>
        <script>
            $(document).ready(function() {
                getTotalCountAndInitPaginator();
            });

            function getTotalCountAndInitPaginator() {
                $.ajax({
                    type: "get",
                    url: "/book/getBookCount",
                    success(result) {
                        if (result.resultCodeEnum == "SUCCESS") {
                            var totalCounts = result.data;
                            if (totalCounts === 0) {
                                $("#pageContainer").hide();
                                $('.bookContainer table tbody').html("");
                            } else {
                                $("#pageContainer").show();
                                // 初始化分页控件
                                $("#pageContainer").jqPaginator({
                                    totalCounts: totalCounts,
                                    pageSize: 5,
                                    visiblePages: 5,
                                    currentPage: 1,
                                    first: '<li class="page-item"><a class="page-link">首页</a></li>',
                                    prev: '<li class="page-item"><a class="page-link" href="javascript:void(0);">上一页<\/a><\/li>',
                                    next: '<li class="page-item"><a class="page-link" href="javascript:void(0);">下一页<\/a><\/li>',
                                    last: '<li class="page-item"><a class="page-link" href="javascript:void(0);">最后一页<\/a><\/li>',
                                    page: '<li class="page-item"><a class="page-link" href="javascript:void(0);">{{page}}<\/a><\/li>',
                                    onPageChange: function (page, type) {
                                        getBookList(page, totalCounts);
                                    }
                                });
                            }
                        }
                    },
                    error(xhr) {
                        if (xhr.status == 401) {
                            alert(xhr.responseText);
                            location.href = './login.html';
                        } else if (xhr.status == 403) {
                            alert(xhr.responseText);
                        } else {
                            alert('HTTP请求失败,状态码: ' + xhr.status);
                        }
                    }
                });
            }

            function getBookList(page, totalCounts) {
                $.ajax({
                    type: "get",
                    url: "/book/getBookList",
                    data: {
                        "currentPage": page,
                        "pageSize": 5
                    },
                    success(result) {
                        if (result.resultCodeEnum == "SUCCESS") {
                            let bookInfoList = result.data;
                            let finalHTML = '';
                            for (let i = 0; i < bookInfoList.length; i++) {
                                finalHTML += '<tr> <td><input type="checkbox" name="selectBook" value="1" id="selectBook" class="book-select"></td>';
                                finalHTML += '<td>';
                                finalHTML += bookInfoList[i].bookId;
                                finalHTML += '</td>';
                                finalHTML += '<td>';
                                finalHTML += bookInfoList[i].bookName;
                                finalHTML += '</td>';
                                finalHTML += '<td>';
                                finalHTML += bookInfoList[i].author;
                                finalHTML += '</td>';
                                finalHTML += '<td>';
                                finalHTML += bookInfoList[i].count;
                                finalHTML += '</td>';
                                finalHTML += '<td>';
                                finalHTML += bookInfoList[i].price;
                                finalHTML += '</td>';
                                finalHTML += '<td>';
                                finalHTML += bookInfoList[i].publish;
                                finalHTML += '</td>';
                                finalHTML += '<td>';
                                finalHTML += bookInfoList[i].statusCN;
                                finalHTML += '</td>';
                                finalHTML += '<td> <div class="op"> <a href="book_update.html?bookId=' + bookInfoList[i].bookId + '">修改</a> <a href="javascript:void(0)" onclick="deleteBook(' + bookInfoList[i].bookId + ')">删除</a>';
                                finalHTML += '</div> </td> </tr>';
                            }
                            $('.bookContainer table tbody').html(finalHTML);
                            // 如果没有数据且不是第一页，自动跳转到上一页
                            if (bookInfoList.length === 0 && page > 1) {
                                $("#pageContainer").jqPaginator('option', 'currentPage', page - 1);
                            }
                        } else {
                            alert(result.message);
                        }
                    },
                    error(xhr) {
                        if (xhr.status == 401) {
                            alert(xhr.responseText);
                            location.href = './login.html';
                        } else if (xhr.status == 403) {
                            alert(xhr.responseText);
                        } else {
                            alert('HTTP请求失败,状态码: ' + xhr.status);
                        }
                    }
                });
            }

            function deleteBook(id) {
                let isDelete = confirm("确认删除?");
                if (isDelete) {
                    // 删除图书
                    // 请求后端删除数据
                    $.ajax({
                        type: "put",
                        url: "/book/deleteBook",
                        data: {
                            "bookId": id
                        },
                        success(result) {
                            if (result.data) {
                                alert("删除成功");
                            } else {
                                alert('删除失败');
                            }
                        },
                        error(xhr) {
                            if (xhr.status == 401) {
                                alert(xhr.responseText);
                                location.href = './login.html';
                            } else if (xhr.status == 403) {
                                alert(xhr.responseText);
                            } else {
                                alert('HTTP请求失败,状态码: ' + xhr.status);
                            }
                        }
                    });
                    // 删除后刷新分页和数据
                    getTotalCountAndInitPaginator();
                }
            }

            function batchDelete() {
                let isDelete = confirm("确认批量删除?");
                if (isDelete) {
                    // 获取复选框的bookId
                    let ids = [];
                    $("input[name='selectBook']:checked").each(function () {
                        // 获取当前行的bookId
                        // 假设checkbox在<tr>的第一个<td>，bookId在第二个<td>
                        let bookId = $(this).closest('tr').find('td').eq(1).text().trim();
                        if (bookId) {
                            ids.push(bookId);
                        }
                    });

                    if (ids.length === 0) {
                        alert('请先选择要删除的图书');
                        return;
                    }

                    $.ajax({
                        type: "put",
                        url: "/book/batchDeleteBook",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success(result) {
                            if (result.data) {
                                alert('批量删除成功');
                            } else {
                                alert('批量删除失败');
                            }
                        },
                        error(xhr) {
                            if (xhr.status == 401) {
                                alert(xhr.responseText);
                                location.href = './login.html';
                            } else if (xhr.status == 403) {
                                alert(xhr.responseText);
                            } else {
                                alert('HTTP请求失败,状态码: ' + xhr.status);
                            }
                        }
                    });
                }
            }
        </script>
    </div>
</body>

</html>